/*jshint esversion: 9 */
//获取图片的主题色
import ColorThief from 'colorthief';
import {localStorageX} from "storagex-js";
const themeColors = localStorageX(  //主题色列表(缓存已经计算过的图片链接) 本地化
    "ImgThemeColorsContainer",
    {},
);
export function getThemeColor(imgUrl){ //获取img主题色
    return new Promise((resolve,reject)=>{
        if(themeColors[imgUrl] === false){  //表示之前处理过这个链接是错误的
            reject("rgb(255, 255, 255)");  //错误后默认为白色
            return;
        }
        if(themeColors[imgUrl]){
            resolve(themeColors[imgUrl]);
            return;
        }
        setTimeout(()=>{
            const colorThief = new ColorThief();
            const img = new Image();
            img.crossOrigin = 'Anonymous';
            img.src = imgUrl;
            img.addEventListener('load', ()=>{
                let themeColor = colorThief.getColor(img);
                let bgColor = 'rgb('+themeColor[0]+','+themeColor[1]+','+themeColor[2]+')';
                themeColors[imgUrl] = bgColor;
                resolve(bgColor);
            });
            img.addEventListener('error', ()=>{  //加载错误清空日志
                themeColors[imgUrl] = false; 
                // console.clear();  //开发版则不需要
                reject("rgb(255, 255, 255)");  //错误后默认为白色
            });
        },0);
    });
}
